package com.jintoufs.web.action.activiti;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jhj.common.util.JhjResponseUtil;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.domain.activiti.Activiti;
import com.jintoufs.domain.activiti.ActivitiProduct;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.constants.WxConstant;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.activiti.ActivitiService;
import com.jintoufs.service.hotel.HotelRoomService;
import com.jintoufs.service.scene.SceneTicketService;
import com.jintoufs.service.tour.TourRouteService;
import com.jintoufs.web.action.support.JqgridPage;
import com.jintoufs.web.action.support.SupportAction;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jintoufs.util.ResponseUtil.writeInfo;

/**
 * 活动管理
 * Created by xufei on 2017/12/19.
 */
@Controller
@Scope("prototype")
@RequestMapping("/activiti")
public class ActivitiAction extends SupportAction {

    @Resource
    private ActivitiService activitiService;
    @Resource
    private HotelRoomService hotelRoomService;
    @Resource
    private SceneTicketService sceneTicketService;
    @Resource
    private TourRouteService tourRouteService;


    /**
     * 活动信息查询
     * @return
     * @throws IOException
     */
    @RequestMapping("/list")
    public String list() throws IOException {
        return "activiti/list";
    }

    @RequestMapping("/query")
    @ResponseBody
    public JqgridPage query(int page, int rows, String sidx, String sord, String filters) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_ = null;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Map<String,Object>> list = activitiService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
                pageInfo.getList());
    }

    /**
     * input.do?id= 进入活动编辑与新增页面 <br>*
     * @param id    活动Id
     * @param model
     * @return
     */
    @RequestMapping(value = "input", method = RequestMethod.GET)
    public String input(Integer id, Model model) {
        Activiti entity = null;
        Map map = new HashMap();
        // 是否为编辑保存
        Boolean isEdit = false;

        if (id != null) {
            // 修改
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("id", id);
            List<Map> list = activitiService.queryByParams(params);
            if (list != null && list.size() > 0) {
                map = list.get(0);
            }
            isEdit = true;
        } else {
            // 新增
        }

        model.addAttribute("isEdit", isEdit);
        model.addAttribute("entity", map);
        return "activiti/update";
    }


    /**
     * 获取详细信息
     */
    @RequestMapping("/getDetail")
    @SystemControllerLog(description = "查看活动详细信息")
    public String getDetail(Integer id, Model model) {
        Activiti result = new Activiti();
        if (id != null && id != 0) {
            result = activitiService.getById(id);
        }
        model.addAttribute("entity", result);
        model.addAttribute("isEdit", "view");
        model.addAttribute("title", "活动详细信息");
        return "activiti/detail";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    @SystemControllerLog(description = "新增活动")
    public AjaxMsg save(Activiti activiti,String type,String valueId, HttpServletResponse response) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        String error = null;
        if(activiti.getName() == null && "".equals(activiti.getName())){
            error = "活动名称不能为空！";
        }
        if(activiti.getImgUrl() == null && "".equals(activiti.getImgUrl())){
            error = "图片路径不能为空！";
        }
        try {
            Activiti result = activitiService.save(activiti);
            if (result!=null){
                ActivitiProduct activitiProduct = new ActivitiProduct();
                activitiProduct.setId(getUUID());
                activitiProduct.setValueId(valueId);
                switch (type){
                    case Constants.ORDER_TYPE_HOTEL:
                        activitiProduct.setTypeId(WxConstant.ACTIVITI_TYPE_HOTEL);
                        break;
                    case Constants.ORDER_TYPE_SCENE:
                        activitiProduct.setTypeId(WxConstant.ACTIVITI_TYPE_SCENE);
                        break;
                    case Constants.ORDER_TYPE_TOUR:
                        activitiProduct.setTypeId(WxConstant.ACTIVITI_TYPE_TOUR);
                        break;
                        default:
                            break;
                }
                activitiProduct.setActivitiId(activiti.getId());
                activitiService.insertActivitiProduct(activitiProduct);
            }
            ajaxMsg.setMessage("新建成功。");
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("系统错误。");
        }
        return ajaxMsg;
    }


    @RequestMapping("edit")
    @ResponseBody
    @SystemControllerLog(description = "修改资源")
    public AjaxMsg edit(Activiti activiti, HttpServletResponse response) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            activitiService.update(activiti);
            ajaxMsg.setMessage("更新成功。");
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode("500");
            ajaxMsg.setMessage("系统错误");
        }
        return ajaxMsg;
    }



    @RequestMapping("delete")
    @SystemControllerLog(description = "删除活动")
    public void delete(HttpServletResponse response,Integer[] id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            for (Integer _id:id){
                activitiService.delete(_id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DataIntegrityViolationException) {
                ajaxMsg.setCode("500");
                ajaxMsg.setMessage("活动还在使用中，删除失败！");
            }
        }
        writeInfo(response, JSON.toJSONString(ajaxMsg));
    }

    @RequestMapping("/create")
    @SystemControllerLog(description = "创建活动")
    public String create(String type,String valueId,Model model){
        Map<String,Object> entity = new HashMap<>();
        Map<String,Object> param = new HashMap<>();
        param.put("id",valueId);
        switch (type){
            case Constants.ORDER_TYPE_HOTEL:
                entity = hotelRoomService.selectByParams(param).get(0);
                entity.put("jiesuanPrice",entity.get("retailPrice"));
                break;
            case Constants.ORDER_TYPE_SCENE:
                entity = sceneTicketService.selectByParams(param).get(0);
                entity.put("jiesuanPrice",entity.get("orignPrice"));
                break;
            case Constants.ORDER_TYPE_TOUR:
                entity = tourRouteService.getByParams(param).get(0);
                entity.put("price",entity.get("totalFee"));
                entity.put("jiesuanPrice",entity.get("distributionPrice"));
            default:
                break;
        }
        model.addAttribute("entity",entity);
        model.addAttribute("type",type);
        model.addAttribute("valueId",valueId);
        return "activiti/input";
    }

}
